package com.bskj.common.utils;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.alibaba.fastjson.JSONObject;
import com.bskj.common.constants.CommonConstatns;
import com.bskj.common.utils.decode.Base64;

/**
 * 加密
 *
 * @author lishi
 * @date 2017-12-18 上午11:28:15
 */
public class EncryptUtil {

	public static final String KEY_ALGORITHM = "AES";
	public static final String CIPER_ALGORITHM = "AES";

	/**
	 * 加密
	 *
	 * @param content  需要加密的内容
	 * @param password 加密密码
	 * @return
	 */
	public static String encrypt(String content, String password) throws Exception {
		SecretKeySpec key = new SecretKeySpec(password.getBytes(), KEY_ALGORITHM);

		Cipher cipher = Cipher.getInstance(CIPER_ALGORITHM);// 创建密码器
		byte[] byteContent = content.getBytes("utf-8");
		cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
		byte[] result = cipher.doFinal(byteContent);
		return parseByte2HexStr(result);
	}

	public static String encrypt(String contentd) throws Exception {
		return encrypt(contentd, CommonConstatns.AES_KEY);
	}

	/**
	 * 解密
	 *
	 * @param str  待解密内容
	 * @param password 解密密钥
	 * @return
	 */
	public static String decrypt(String str, String password) throws Exception {
		byte[] content = parseHexStr2Byte(str);
		SecretKeySpec key = new SecretKeySpec(password.getBytes(), KEY_ALGORITHM);

		Cipher cipher = Cipher.getInstance(CIPER_ALGORITHM);// 创建密码器
		cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
		byte[] result = cipher.doFinal(content);
		return new String(result, "UTF-8");
	}

	public static String decrypt(String string) throws Exception {
		return decrypt(string, CommonConstatns.AES_KEY);
	}

	public static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}

	public static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	public static String getMD5(String str) {
		return getMD5(str,false);
	}
	
	public static String getMD5(String sourceStr,boolean is16) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
            if(is16) {
            	return buf.toString().substring(8, 24);
            } else {
            	return result;
            }
        } catch (NoSuchAlgorithmException e) {
            System.out.println(e);
        }
        return result;
    }

	/** 
	 * 对字符串md5加密(大写+数字) 
	 * 
	 * @param str 传入要加密的字符串 
	 * @return  MD5加密后的字符串 
	 */

	public static String MD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象  
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要  
			mdInst.update(btInput);
			// 获得密文  
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式  
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String enBase64(String text) throws Exception {
		return new String(Base64.encodeBase64(text.getBytes("UTF-8")), "UTF-8");
	}

	public static String deBase64(String text) throws Exception {
		return new String(Base64.decodeBase64(text.getBytes("UTF-8")), "UTF-8");
	}

	public static String getSHA256StrJava(String str) {
		MessageDigest messageDigest;
		String encodeStr = "";
		try {
			messageDigest = MessageDigest.getInstance("SHA-256");
			messageDigest.update(str.getBytes("UTF-8"));
			encodeStr = parseByte2HexStr(messageDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encodeStr;
	}

	public static void main(String[] args) throws Exception {
//		JSONObject jsonRequestData = new JSONObject();
//		jsonRequestData.put("version", "1.0");
//		jsonRequestData.put("charset", "UTF-8");
//
//		jsonRequestData.put("signType", "SHA-256");
//
//		JSONObject reqObj = new JSONObject();
//		reqObj.put("dateTime", DateTimeUtil.date2String(new Date(), "yyyyMMddHHmmss"));
//		reqObj.put("txCode", "FBPK");
//		reqObj.put("branchNo", "0731");
//		reqObj.put("merchantNo", "000034");
//		jsonRequestData.put("reqData", reqObj);
//
//		String src = StringUtils.dictSort(reqObj) + "&s91A23P37aR0b96W";
//		System.out.println(src);
//		String signStr = getSHA256StrJava(src);
//		System.out.println(signStr);
//		jsonRequestData.put("sign", signStr);
//
//		String reqUrl = "http://121.15.180.72/CmbBank_B2B/UI/NetPay/DoBusiness.ashx";
//		System.out.println(jsonRequestData);
//
//		Map<String, String> jsonMap = new HashMap<>();
//		jsonMap.put("jsonRequestData", jsonRequestData.toJSONString());
//
//		System.out.println(jsonMap);
//		String responeStr = HttpClientUtils.postRequest(reqUrl, jsonMap);
//		System.out.println(responeStr);

//				JSONObject paramObj = new JSONObject();
//				paramObj.put("uri", "/parkInfo/park");
		//		paramObj.put("uri", "/parkInfo/offlineDataBackup");
		//		paramObj.put("uri", "/parkInfo/getCarNoInfo");
		//		paramObj.put("uri", "/parkInfo/confirmReceiveMoney");

//				paramObj.put("parkLotCustomerId", "10131");
//				paramObj.put("uuid", "1530024985566a8c7139");
//				paramObj.put("carNo", "湘A8K80D");

		//		paramObj.put("parkInfoId", "22685");
		//		paramObj.put("chargeType", "1");

//				paramObj.put("inTime", DateTimeUtil.date2String(new Date()));
//				paramObj.put("outTime", DateTimeUtil.date2String(new Date()));
//				paramObj.put("charge", "1");
//				paramObj.put("boxNo", "泊数测试岗亭");
//				System.out.println(encrypt(paramObj.toJSONString()));

		//		String str = "C1F11E61B0AE467980DE196243C594F2F7EF916170909B7B8DF2D2C8DF4E4E5153DFF0826893DA0C5DDEDF9BC896B88D16600194633552E11F866041C8B6D6AAD9A588A828D19C70C82C4A83550339F70F40F6FE3AC0F964D1D992A350FD6E41B5BC299005B754922BAF7733FAF3F2D143DD83766D9C72D1B605ECFCEA7D5ABEBE3BA68F0606D2BD2BAE7449084FECB00EFC745A63EA7AA48C9F3F9A69E10599A606A9605804D61F597530B4DE0FAAEF9CF9E58C8DFE097DB1895CC08F5C9C576BA7C2D3F38E90A16B7475F319381CFC";
		//		System.out.println(decrypt("504847B0B5C597A9C561EED4B118796E88BF3934885513635EC73CE265314F7DB3F393AA9FE094C93D955D7242510C360441E0E17DCB59CC3EF1E4C0ABFEFE3C338827EEFB9CB2EE5D572CCD0AAFD51981B7BECD02E173DF255AC1F554CE1D65962085F842EF330A6D0C610231970F5428B91CCE8258F8BF245B0589F6303FCD6962D49154BB1D19E383465B80C3ADDC2C858FF247DB405034D07FE6781510FA9673CE1BC1D8531B75214B43941859B6B975964FF92DD24A278958096947D47E"));
		//		String data = "eyJzdWJqZWN0Ijoi6bqT6LC35L+h5oGv5riv5YGc6L2m5Zy65YGc6L2m6LS5Iiwib3V0VHJhZGVObyI6IjEwMTAwODc5ODI4MzA0NTI3MzYiLCJyZW1hcmsiOiLpupPosLfkv6Hmga/muK/lgZzovablnLrlgZzovabotLkiLCJib2R5Ijoi6bqT6LC35L+h5oGv5riv5YGc6L2m5Zy65YGc6L2m6LS5IiwiaXNBbGxvdyI6IkZBSUwifQ==";
		//		System.out.println(deBase64(data));
		//		long a=1535126399000l;
		//		System.out.println(DateTimeUtil.date2String(new Date(a)));
		//		System.out.println(EncryptUtil.getMD5("abc123456"));
		String url = "http://pay.szfarcn.com/App/UpTicketNo.aspx?ParkNo=13574117092&OperateType=new&CarNo=湘G36953&DistType=3&DistFee=1000&StartTime=20181227000000&EndTime=20191227000000&CustomerID=30000";
		String pKey = "BC0C0BEC";
		String token = getMD5(url.toLowerCase() + pKey.toLowerCase());
		url = url +"&Token=" + token;
		System.out.println(url);
		String respone = HttpClientUtils.doGet(url);
		//URLEncoder.encode(url, "utf-8")
		System.out.println(respone);
		
	}
}
